package com.le.enhance.class5;

import org.junit.Test;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 判断一棵树是否是完全二叉树
 * 思路:
 * 完全二叉树每层都是从左向右依次排列
 */
public class Code_01_IsCBT {

    public static class Node {
        public int value;
        Node left;
        Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    public static boolean isCBT(Node head) {
        if (head == null) {
            return true;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.add(head);
        Node L = null;
        Node R = null;
        boolean leaf = false;
        while (!queue.isEmpty()) {
            head = queue.poll();
            L = head.left;
            R = head.right;
            if ((L == null && R != null) || (leaf && (L != null || R != null))) {
                return false;
            }

            if (L != null) {
                queue.offer(L);
            }
            if (R != null) {
                queue.offer(R);
            } else {
                leaf = true;
            }
        }

        return true;
    }

    @Test
    public void test(){
        Node head = new Node(4);
        head.left = new Node(2);
        head.right = new Node(6);
//        head.left.left = new Node(1);
//        head.left.right = new Node(3);
        head.right.left = new Node(5);
        System.out.println(isCBT(head));
    }
}
